<template>
  <div class="search">
    <el-container>
      <el-header>
        <h2>文件搜索</h2>
        <el-button @click="$router.push('/')">返回首页</el-button>
      </el-header>
      <el-main>
        <!-- 搜索输入区域 -->
        <div class="search-input-section">
          <SearchInput
            v-model:query="searchStore.query"
            v-model:search-type="searchStore.searchType"
            :is-searching="searchStore.isSearching"
            :recent-searches="searchStore.recentSearches"
            @search="handleSearch"
            @clear="handleClear"
            @clear-history="searchStore.clearSearchHistory"
            @remove-history="searchStore.removeFromSearchHistory"
          />
        </div>

        <!-- 搜索过滤器 -->
        <div class="search-filters-section" v-if="showFilters">
          <SearchFilters
            v-model:options="searchStore.searchOptions"
            v-model:content-options="searchStore.contentSearchOptions"
            v-model:advanced-criteria="searchStore.advancedCriteria"
            :search-type="searchStore.searchType"
            :available-versions="historyStore.versions"
            @filter-change="handleFilterChange"
          />
        </div>

        <!-- 搜索结果区域 -->
        <div class="search-results-section" v-if="searchStore.hasResults || searchStore.error">
          <SearchResults
            :results="searchStore.paginatedResults"
            :search-type="searchStore.searchType"
            :query="searchStore.query"
            :total-results="searchStore.totalResults"
            :current-page="searchStore.currentPage"
            :total-pages="searchStore.totalPages"
            :page-size="searchStore.pageSize"
            :is-loading="searchStore.isSearching"
            :error="searchStore.error"
            @page-change="searchStore.goToPage"
            @page-size-change="searchStore.setPageSize"
            @file-select="handleFileSelect"
            @recover-file="handleRecoverFile"
            @batch-recover="handleBatchRecover"
          />
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="!searchStore.hasResults && !searchStore.isSearching && !searchStore.error">
          <el-empty description="输入关键词开始搜索">
            <el-button type="primary" @click="showFilters = !showFilters">
              {{ showFilters ? '隐藏' : '显示' }}高级搜索
            </el-button>
          </el-empty>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import router from '../router'
import { ElMessage } from 'element-plus'
import { useSearchStore } from '../stores/search'
import { useHistoryStore } from '../stores/history'
import { useRecoveryStore } from '../stores/recovery'
import SearchInput from '../components/SearchInput.vue'
import SearchFilters from '../components/SearchFilters.vue'
import SearchResults from '../components/SearchResults.vue'
import type { SearchResult, ContentSearchResult } from '../types/basic'

// Using imported router directly
const searchStore = useSearchStore()
const historyStore = useHistoryStore()
const recoveryStore = useRecoveryStore()

const showFilters = ref(false)

// 处理搜索
async function handleSearch(query: string) {
  if (!query.trim()) {
    searchStore.clearResults()
    return
  }

  try {
    switch (searchStore.searchType) {
      case 'filename':
        await searchStore.searchByFileName(query)
        break
      case 'content':
        await searchStore.searchByContent(query)
        break
      case 'advanced':
        await searchStore.advancedSearch()
        break
    }
  } catch (error) {
    ElMessage.error('搜索失败，请重试')
    console.error('Search failed:', error)
  }
}

// 处理清空搜索
function handleClear() {
  searchStore.clearResults()
  searchStore.setQuery('')
}

// 处理过滤器变化
function handleFilterChange() {
  // 如果有当前查询，重新执行搜索
  if (searchStore.query.trim()) {
    handleSearch(searchStore.query)
  }
}

// 处理文件选择
function handleFileSelect(result: SearchResult | ContentSearchResult) {
  // 导航到文件详情或差异对比页面
  router.push({
    name: 'diff-viewer',
    query: {
      versionId: result.versionId,
      fileId: result.fileId,
      path: result.originalPath
    }
  })
}

// 处理文件恢复
async function handleRecoverFile(result: SearchResult | ContentSearchResult) {
  try {
    const task = {
      versionId: result.versionId,
      fileId: result.fileId,
      originalPath: result.originalPath,
      targetPath: result.originalPath
    }
    
    await recoveryStore.recoverSingle(task)
    ElMessage.success(`文件 ${result.fileName} 恢复成功`)
  } catch (error) {
    ElMessage.error('文件恢复失败')
    console.error('File recovery failed:', error)
  }
}

// 处理批量恢复
async function handleBatchRecover(results: (SearchResult | ContentSearchResult)[]) {
  try {
    const tasks = results.map(result => ({
      versionId: result.versionId,
      fileId: result.fileId,
      originalPath: result.originalPath,
      targetPath: result.originalPath
    }))
    
    // Add tasks to recovery queue and then recover
    recoveryStore.addMultipleToQueue(tasks)
    await recoveryStore.recoverBatch()
    ElMessage.success(`成功恢复 ${results.length} 个文件`)
  } catch (error) {
    ElMessage.error('批量恢复失败')
    console.error('Batch recovery failed:', error)
  }
}

// 监听搜索类型变化
watch(() => searchStore.searchType, (newType) => {
  if (newType === 'advanced') {
    showFilters.value = true
  }
})

// 组件挂载时初始化
onMounted(async () => {
  // 确保历史版本已加载
  if (historyStore.versions.length === 0) {
    await historyStore.loadVersions()
  }
  
  // 构建搜索索引
  try {
    await searchStore.buildSearchIndex()
  } catch (error) {
    console.warn('Failed to build search index:', error)
  }
})
</script>

<style scoped>
.search {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--el-color-primary-light-3);
  padding: 0 20px;
  flex-shrink: 0;
}

.el-main {
  padding: 20px;
  flex: 1;
  overflow: auto;
}

.search-input-section {
  margin-bottom: 20px;
}

.search-filters-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: var(--el-color-info-light-9);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.search-results-section {
  flex: 1;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>